package com.houning.runner;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.Rows;
import com.deepoove.poi.data.Tables;
import com.houning.config.ServerProperties;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class InitRunner implements ApplicationRunner {
    private final ResourceLoader resourceLoader;
    private final ServerProperties serverProperties;

    @Override
    public void run(ApplicationArguments args) {
        generate();
    }

    @SneakyThrows
    public void generate() {
        Map<String, Object> tablesMap = new HashMap<>();
        int tableCount = 3;
        List<Map<String, Object>> tables = new ArrayList<>();
        for (int i = 0; i < tableCount; i++) {
            Map<String, Object> contentMap = new HashMap<>();
            contentMap.put("title", "表格: " + (i + 1));
            tables.add(contentMap);

            RowRenderData row0 = Rows.of("姓名", "学历").textColor("FFFFFF")
                    .bgColor("4472C4").center().create();
            RowRenderData row1 = Rows.create("李四", "博士");
            contentMap.put("content", Tables.create(row0, row1));
        }
        tablesMap.put("tables", tables);
        try (InputStream inputStream = readTemplate()) {
            XWPFTemplate template = XWPFTemplate.compile(inputStream).render(tablesMap);
            template.writeAndClose(new FileOutputStream("output2.docx"));

            System.out.println("Generating " + tableCount + " tables successful!");
        }
    }

    @SneakyThrows
    public InputStream readTemplate() {
        Resource resource = resourceLoader.getResource(serverProperties.getTemplatePath());
        return resource.getInputStream();
    }
}
